import {getLoginUser} from "../../service/user";
import {goPay} from "../../service/order";
import {simpleGet} from "../../utils/request";
import {showToast} from "../../utils/tool";

const app = getApp()
const global = app.globalData

Page({
    data: {
        nav:{
            height:false,
            color:"#fff",
        },
        options:{},
        imageUrl: global.imageUrl,
        info:null,
        user:null,
    },
    onLoad: function (options = {}) {
        this.init(options)
    },

    numChange(e){
        const {value} = e.detail
        const {index} = e.currentTarget.dataset
        const {info} = this.data
        const goods = info.goodsUl[index]
        const oldNum = goods.num || 0
        let num = parseInt(value)

        if (goods.once_buy_num != -1 && num > goods.once_buy_num){
            num = goods.once_buy_num
            showToast(`每次限购${goods.once_buy_num}件`);
        }

        if (goods.total_num != -1 && num > goods.total_num){
            num = goods.total_num
            showToast(`仅剩${goods.total_num}件`);
        }

        const oldGoodsPrice = parseFloat(goods.active_price) * oldNum
        const oldTotal = info.total
        const newGoodsPrice = parseFloat(goods.active_price) * num
        const newTotal = parseFloat(oldTotal - oldGoodsPrice + newGoodsPrice)

        this.setData({
            [`info.goodsUl[${index}].num`]:num,
            [`info.total`]: newTotal
        })
    },

    buyClick(){
        const {info} = this.data
        if (info.total == 0){
            showToast("请选择要购买的商品")
            return;
        }
        const goodsUl = info.goodsUl.map(item => {
            item.image = info.image
            return item
        })
        console.log("goodsUl", goodsUl)
        goPay({
            goodsUl:goodsUl,
            order_type:'follow',
        })
    },


    /**
     * 图片预览
     */
    imagePreview: function (e) {
        let {images,index} = e.target.dataset
        this.setData({
            'imgPreview.images': images,
            'imgPreview.show': true,
            'imgPreview.index': index,
        })

    },

    async init(options){
        options = options||{}
        const info = await simpleGet("/detail/follow", {id:options.id})
        const user = await getLoginUser()
        // 添加默认的商品数量
        if (info) {
            info.num = 0
            info.total = 0
        }

        this.setData({
            info,
            user
        })
    }
});
